import { Injectable } from '@angular/core';
import {
  Http,
  Response,
  URLSearchParams,
  Headers,
  RequestOptions,
  RequestOptionsArgs
} from '@angular/http';

import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { environment } from '../../../environments/environment';
import { HttpService } from './auth.service';
import { LoginService } from './login.service';

@Injectable()
export class RecipesManageService {
    private apiBaseUrl = environment.apiBaseUrl;

    constructor (
        private http: Http,
        private loginService: LoginService,
        private myHttp: HttpService,
    ) {}

    // http://47.100.161.202:8080/admin/channel/list
    // 获取列表接口
    getRecipesList(param: object): Observable<object> {
        const params: URLSearchParams = new URLSearchParams();
        // params.set('name', param['name']);
        // // 食谱名称，模糊查询
        // params.set('tagId', param['tagId']);
        // // 标签id
        // params.set('flowStatus', param['flowStatus']);
        // // 流程状态：
        // //      待产品部完善
        // //      待运营部完善
        // //      待市场部完善
        // //      完成
        // params.set('pubStatus', param['pubStatus']);
        // // 上下架状态:
        // // 未上架
        // // 上架
        // params.set('startDate', param['startDate']);
        // // 创建日期开始
        // params.set('endDate', param['endDate']);
        // // 创建日期结束
        // params.set('channelId', param['channelId']);
        // // 渠道id
        // params.set('pageSize', param['pageSize']);
        // params.set('pageNumber', param['pageNumber']);

        // 获取食谱列表
        // const pamName = 'name=' + param['name'];
        params.set('name', param['name']);

        // const pamTag = '&tagId=' + param['tagId'];
        params.set('tagId', param['tagId']);

        // const pamflowStatus = '&flowStatus=' + param['flowStatus'];
        params.set('flowStatus', param['flowStatus']);

        // const pampubStatus = '&pubStatus=' + param['pubStatus'];
        params.set('pubStatus', param['pubStatus']);

        // const pamstartDate = '&startDate=' + param['startDate'];
        params.set('startDate', param['startDate']);

        // const pamendDate = '&endDate=' + param['endDate'];
        params.set('endDate', param['endDate']);

        // let pamchannelId = '&channelId=';
        // param['channelId'] ? pamchannelId += param['channelId'] : pamchannelId += '';
        params.set('channelId', param['channelId'] ? param['channelId'] : '' );

        // const pampageSize = '&pageSize=' + param['pageSize'];
        params.set('pageSize', param['pageSize']);

        // const pampageNumber = '&pageNumber=' + param['pageNumber'];
        params.set('pageNumber', param['pageNumber']);

        return this.http.get(this.apiBaseUrl + 'admin/recipe/list?',  {params})
                .map(res => res.text() ? res.json() : {})
                .catch(this.handleError);
    }

    // 获取食谱详情
    getRecipe(id): Observable<object> {
        return this.http.get(this.apiBaseUrl + 'admin/recipe/getRecipe?id=' + id)
                .map(res => res.text() ? res.json() : {})
                .catch(this.handleError);
    }

    // 新增食谱(基本信息)接口
    postCreateRecipes(param: object): Observable<object> {
        const data = new URLSearchParams();
        const params = {
            // name: param['name'],
            // channelIds: param['channelIds'],        // 渠道id  数组
            // tagAttributeIds: param['tagAttributeIds'],  // 标签id  数组
            // specification: param['specification'],      // 成品规格
            // resPerson: param['resPerson'],  // 负责人
            // recipeMaterialList: param['recipeMaterialList']
            // 食谱配方
            // {
            //     Material: {
            //         id: 1,    // 原料id
            //     },
            //     dosage: '1g', // 用量
            //     main: true    // 主要原料
            // }
        };
        // name
        // const pamNameUrl = '?name=' + param['name'];
        data.set('name', param['name']);

        // channelIds  recipeChannelList [0].channel.id=1  recipeChannelList [0].price=10.5
        param['channelIdsArray'].forEach((ids, index) => {
            data.set(`recipeChannelList[${index}].channel.id`, ids.id);
            data.set(`recipeChannelList[${index}].price`, ids.price);
        });

        // pamChannelIds = pamChannelIds.replace(/\,$/g, i => '');
        // tagAttributeIds
        let pamtagAttributeIds = '';
        param['tagAttributeIdsArray'].forEach(ids => {
            pamtagAttributeIds += ids['id'] + ',';
        });
        pamtagAttributeIds = pamtagAttributeIds.replace(/\,$/g, i => '');
        data.set('tagAttributeIds', pamtagAttributeIds);

        // specification
        // let pamspecification = '&specification=' + param['specification'];
        data.set('specification', param['specification']);

        // sop
        // let pamSop = '&sop=' + param['sop'];
        data.set('sop', param['sop']);

        // resPerson
        const pamresSon = param['resPersonArray'].find(i => i['employeeId'] ===  param['resPerson']);
        // let pamresPerson = '&resPerson=' + pamresSon['employeeName'];
        data.set('resPerson', pamresSon['employeeName']);

        // employeeId
        // const pamemployeeId = '&employeeId=' + pamresSon['employeeId'];
        data.set('employeeId', pamresSon['employeeId']);

        // recipeMaterialList
        // let pamrecipeMaterialList = '';
        param['recipeMaterialList'].forEach((label, index) => {
            data.set(`recipeMaterialList[${index}].Material.id`, label['Material']['id']);
            data.set(`recipeMaterialList[${index}].dosage`, label['dosage']);
            data.set(`recipeMaterialList[${index}].main`, label['main']);
        });

        // pamrecipeMaterialList = pamrecipeMaterialList.replace(/\,$/g, i => '');

        return this.http.post(this.apiBaseUrl + 'admin/recipe/save', data)
            .map(res => res.text() ? res.json() : {})
            .catch(this.handleError);
    }

    // 获取方案负责人
    getEmployeeList(): Observable<object> {
        return this.myHttp.get(this.apiBaseUrl + 'admin/recipe/getEmployeeList?token=' + this.loginService.user.token)
                .catch(this.handleError);
    }

    // 修改食谱基本信息接口
    postUpdateRecipes(param: object): Observable<object> {
        const data = new URLSearchParams();
        // name
        // const pamNameUrl = '?name=' + param['name'];
        data.set('id', param['id']);
        data.set('name', param['name']);

        // channelIds  recipeChannelList [0].channel.id=1  recipeChannelList [0].price=10.5
        param['channelIdsArray'].forEach((ids, index) => {
            data.set(`recipeChannelList[${index}].channel.id`, ids.id);
            data.set(`recipeChannelList[${index}].price`, ids.price);
        });

        // pamChannelIds = pamChannelIds.replace(/\,$/g, i => '');
        // tagAttributeIds
        let pamtagAttributeIds = '';
        param['tagAttributeIdsArray'].forEach(ids => {
            pamtagAttributeIds += ids['id'] + ',';
        });
        pamtagAttributeIds = pamtagAttributeIds.replace(/\,$/g, i => '');
        data.set('tagAttributeIds', pamtagAttributeIds);

        // specification
        // let pamspecification = '&specification=' + param['specification'];
        data.set('specification', param['specification']);

        // sop
        // let pamSop = '&sop=' + param['sop'];
        data.set('sop', param['sop']);

        // resPerson
        const pamresSon = param['resPersonArray'].find(i => i['employeeId'] ===  param['resPerson']);
        // let pamresPerson = '&resPerson=' + pamresSon['employeeName'];
        data.set('resPerson', pamresSon['employeeName']);

        // employeeId
        // const pamemployeeId = '&employeeId=' + pamresSon['employeeId'];
        data.set('employeeId', pamresSon['employeeId']);

        // recipeMaterialList
        // let pamrecipeMaterialList = '';
        param['recipeMaterialList'].forEach((label, index) => {
            data.set(`recipeMaterialList[${index}].Material.id`, label['Material']['id']);
            data.set(`recipeMaterialList[${index}].dosage`, label['dosage']);
            data.set(`recipeMaterialList[${index}].main`, label['main']);
        });

        return this.http.post(this.apiBaseUrl + 'admin/recipe/save', data)
            .map(res => res.text() ? res.json() : {})
            .catch(this.handleError);
    }

    // 修改食谱图文信息接口
    postUpdateRecipesInfo(param: object): Observable<object> {
        const data = new URLSearchParams();
        data.set('id', param['id']);
        data.set('description', param['description']);
        data.set('images', param['images']);
        data.set('details', param['details']);

        return this.http.post(this.apiBaseUrl + 'admin/recipe/updateGraphicInfo', data)
            .map(res => res.text() ? res.json() : {})
            .catch(this.handleError);
    }

    // 修改食谱上下架设置接口
    postUpdateRecipesPubStatus(param: object): Observable<object> {
        const data = new URLSearchParams();
        data.set('id', param['id']);
        data.set('pubStatus', param['pubStatus']);

        return this.http.post(this.apiBaseUrl + 'admin/recipe/updatePubStatus', data)
            .map(res => res.text() ? res.json() : {})
            .catch(this.handleError);
    }

    // 删除食谱接口
    postDeleteChannel(param: object): Observable<object> {
        const data = new URLSearchParams();
        let paramUrl = ``;
        param['ids'].forEach((pm, index) => {
            if ((index + 1) === param['ids'].length) {
                paramUrl += pm;
            } else {
                paramUrl += pm + ',';
            }
        });
        data.set('ids', paramUrl);
        return this.http.post(this.apiBaseUrl + 'admin/recipe/delete', data)
            .map(res => res.text() ? res.json() : {})
            .catch(this.handleError);
    }

    private extractData(res: Response) {
        const body = res.json();
        return body || { };
    }

    private handleError (error: Response | any) {
        return Observable.throw(error);
    }
}
